package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.*;
import com.itheima.ydd.dto.ArticleDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@Slf4j
@RequestMapping("/ydd_article")
public class YddArticleController {
    @Autowired
    private IYddArticleService articleService;
    @Autowired
    private IYddCateService cateService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private ISysRoleMenuService roleMenuService;

    @GetMapping("/list")
    public ResultData list(Long start_time, Long end_time, String title, Long cateid, Integer page, Integer limit){
        //log.info(start_time.toString());
        //log.info(end_time.toString());

        Page<YddArticle> pageInfo = new Page<>(page, limit);
        Page<ArticleDto> dtoPage = new Page<>();

        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(title != null,YddArticle::getTitle,title);
        queryWrapper.eq(cateid != null ,YddArticle::getCateid,cateid);
        queryWrapper.between(start_time !=null & end_time != null ,YddArticle::getCreateDate,start_time,end_time);
        queryWrapper.orderByDesc(YddArticle::getCreateDate);
        articleService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<YddArticle> articleList = pageInfo.getRecords();
        List<ArticleDto> articleDtoList = articleList.stream().map(item->{
            ArticleDto articleDto = new ArticleDto();
            BeanUtils.copyProperties(item,articleDto);
            Integer cateid1 = Math.toIntExact(item.getCateid());
            YddCate cate = cateService.getById(cateid1);
            if (cate != null){
                articleDto.setCatename(cate.getCatename());
            }

            return articleDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(articleDtoList);
        return ResultData.ok("", PageResult.init(dtoPage.getTotal(), dtoPage.getSize(), dtoPage.getCurrent(), dtoPage.getRecords()));
    }

    @GetMapping("del")
    public ResultData del(Integer id) {
        log.info("文章删除启动");
        YddArticle article = articleService.getById(id);
        if ("1".equals(article.getDefaultData())) {
            return ResultData.error("默认数据无法删除");
        }
        //权限管理
        LambdaQueryWrapper<SysRole> qlw = new LambdaQueryWrapper<>();
        //获取用户登陆的id  转化为string类型  --前端页码传来的值带有【】 ""  所以要去除点
        String userId = UserHolder.getUserId();
        SysUser user1 = userService.getById(userId);
        //分割
        String strip = StringUtils.strip(user1.getRoleId(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            //代替    --去除
            split[i] = StringUtils.replace(split[i], "\"", "");
        }
        qlw.in(SysRole::getId, split);
        List<SysRole> list = roleService.list(qlw);
        List<String> collect = list.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<SysRoleMenu> qlw2 = new LambdaQueryWrapper<>();
        qlw2.in(SysRoleMenu::getRoleId, collect);
        List<SysRoleMenu> list1 = roleMenuService.list(qlw2);
        for (SysRoleMenu roleMenu : list1) {
            String menuId = roleMenu.getMenuId();
            SysMenu menu = menuService.getById(menuId);
            //一级权限
            if ("内容管理".equals(menu.getTitle())) {
                LambdaQueryWrapper<SysMenu> qlw3 = new LambdaQueryWrapper<>();
                qlw3.eq(SysMenu::getPid, menuId);
                List<SysMenu> list2 = menuService.list(qlw3);
                //二级缓存
                for (SysMenu menu1 : list2) {
                    if ("文章管理".equals(menu1.getTitle())) {
                        LambdaQueryWrapper<SysMenu> qwl4 = new LambdaQueryWrapper<>();
                        qwl4.eq(SysMenu::getPid, menu1.getId());
                        List<SysMenu> list3 = menuService.list(qwl4);
                        for (SysMenu menu2 : list3) {
                            //三级缓存
                            if ("删除".equals(menu2.getTitle())) {
                                articleService.removeById(id);
                                return ResultData.ok("删除成功", "");
                            }
                        }
                    }
                }
            }
        }

        return ResultData.error("权限不足不给删除");
    }

    @PostMapping("add")
    public ResultData add(@RequestBody YddArticle article) {
        log.info("新增启动");
        LambdaQueryWrapper<YddArticle> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YddArticle::getTitle,article.getTitle());
        YddArticle article1 = articleService.getOne(lqw);
        if (article1 != null) {
            throw new BusinessException("该文章名已存在，请重新命名");
        }
        //权限管理
        LambdaQueryWrapper<SysRole> qlw = new LambdaQueryWrapper<>();
        //获取用户登陆的id  转化为string类型  --前端页码传来的值带有【】 ""  所以要去除点
        String userId = UserHolder.getUserId();
        SysUser user1 = userService.getById(userId);
        //分割
        String strip = StringUtils.strip(user1.getRoleId(), "[]");
        String[] split = strip.split(",");
        for (int i = 0; i < split.length; i++) {
            //代替    --去除
            split[i] = StringUtils.replace(split[i], "\"", "");
        }
        qlw.in(SysRole::getId, split);
        List<SysRole> list = roleService.list(qlw);
        List<String> collect = list.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        LambdaQueryWrapper<SysRoleMenu> qlw2 = new LambdaQueryWrapper<>();
        qlw2.in(SysRoleMenu::getRoleId, collect);
        List<SysRoleMenu> list1 = roleMenuService.list(qlw2);
        for (SysRoleMenu roleMenu : list1) {
            String menuId = roleMenu.getMenuId();
            SysMenu menu = menuService.getById(menuId);
            //一级权限
            if ("内容管理".equals(menu.getTitle())) {
                LambdaQueryWrapper<SysMenu> qlw3 = new LambdaQueryWrapper<>();
                qlw3.eq(SysMenu::getPid, menuId);
                List<SysMenu> list2 = menuService.list(qlw3);
                //二级缓存
                for (SysMenu menu1 : list2) {
                    if ("标签管理".equals(menu1.getTitle())) {
                        LambdaQueryWrapper<SysMenu> qwl4 = new LambdaQueryWrapper<>();
                        qwl4.eq(SysMenu::getPid, menu1.getId());
                        List<SysMenu> list3 = menuService.list(qwl4);
                        for (SysMenu menu2 : list3) {
                            //三级缓存
                            if ("增加".equals(menu2.getTitle())) {

                                articleService.save(article);

                                return ResultData.ok("新增成功", article);
                            }
                        }
                    }
                }
            }
        }

        return ResultData.error("权限不足不能添加");
    }
    /**
     * 修改时数据回显
     *
     * @param
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id) {

        YddArticle article = articleService.getById(id);
        return ResultData.ok("返回要修改的数据",article);

    }

    /**
     * 修改文章
     *
     * @param
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody ArticleDto articleDto) {
        articleDto.setUpdateDate(System.currentTimeMillis());
        articleService.updateById(articleDto);
        return ResultData.ok("角色修改成功","");
    }
}
